﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsAnswersTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    /// <summary>
    /// Answer Business Object
    /// </summary>

    public class Answers : BOBase
    {


        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected Answers() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        /// <summary>
        /// PKID of the Answer.
        /// </summary>
        public int AnswerID
        {
            get { return _AnswerID; }
            set
            {
                if (_AnswerID != value)
                {
                    if (OnPropertyChanging("AnswerID", _AnswerID, value))
                    {
                        int oldValue = _AnswerID;
                        _AnswerID = value;

                        OnPropertyChanged("AnswerID", oldValue, value);
                    }
                }
            }
        }  private int _AnswerID = -1;

        /// <summary>
        /// QuestionID.
        /// </summary>
        public string QuestionID
        {
            get { return _questionID; }
            set
            {
                if (_questionID != value)
                {
                    if (OnPropertyChanging("QuestionID", _questionID, value))
                    {
                        string oldValue = _questionID;
                        _questionID = value;
                        OnPropertyChanged("QuestionID", oldValue, value);
                    }
                }
            }
        }  private string _questionID = null;


        /// <summary>
        /// Answer.
        /// </summary>
        public string Answer
        {
            get { return _answer; }
            set
            {
                if (_answer != value)
                {
                    if (OnPropertyChanging("Answer", _answer, value))
                    {
                        string oldValue = _answer;
                        _answer = value;
                        OnPropertyChanged("Answer", oldValue, value);
                    }
                }
            }
        }  private string _answer = null;


        /// <summary>
        /// Date/time at which the Answer was created.
        /// </summary>
        public DateTime? AnswerDate
        {
            get { return _AnswerDate; }
            set
            {
                if (_AnswerDate != value)
                {
                    if (OnPropertyChanging("AnswerDate", _AnswerDate, value))
                    {
                        DateTime? oldValue = _AnswerDate;
                        _AnswerDate = value;
                        OnPropertyChanged("AnswerDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _AnswerDate = null;


        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty Answer object.
        /// </summary>
        public static Answers CreateNew()
        {
            Answers obj = new Answers();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;

            obj.AnswerDate = DateTime.Now;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static Answers CreateNew(AnswerCollection collection)
        {
            Answers obj = CreateNew();

            // Get next/unique ID for the new object.
            int minVal = 0;
            foreach (Answers answer in collection)
            {
                if (answer.AnswerID < minVal)
                    minVal = answer.AnswerID;
            }
            obj.AnswerID = --minVal;
            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetAllAnswer

        /// <summary>
        /// Returns a collection of all Answer.
        /// </summary>
        public static AnswerCollection GetAllAnswer()
        {
            AnswersTableAdapter adapter = new AnswersTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsAnswers.AnswersDataTable tbl = adapter.GetData(null);

            AnswerCollection list = new AnswerCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsAnswers.AnswersRow row in tbl.Rows)
                {
                    Answers answer = new Answers();
                    RelationalToObject(answer, row);
                    list.Add(answer);
                }
            }

            return (list);
        }

        #endregion

        #region GetAnswerByID

        /// <summary>
        /// Returns an Answer object for the specified 'AnswerID' or null if no Answer with the specified parameter(s) exists.
        /// </summary>
        public static Answers GetAnswerByID(int answerid)
        {
            AnswersTableAdapter adapter = new AnswersTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsAnswers.AnswersDataTable tbl = adapter.GetData(answerid);

            if (tbl.Rows.Count == 1)
            {
                Answers answer = new Answers();
                RelationalToObject(answer, tbl.Rows[0]);
                return (answer);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'answerid' returned more than one record.");

            return (null);
        }

        #endregion

        #region GetAllAnswerByQuestionID

        /// <summary>
        /// Returns a collection of all Answer.
        /// </summary>
        public static AnswerCollection GetAllAnswerByQuestionID(int questionid)
        {
            AnswersTableAdapter adapter = new AnswersTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsAnswers.AnswersDataTable tbl = adapter.GetDataByQuestionID(questionid);

            AnswerCollection list = new AnswerCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsAnswers.AnswersRow row in tbl.Rows)
                {
                    Answers answer = new Answers();
                    RelationalToObject(answer, row);
                    list.Add(answer);
                }
            }

            return (list);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified Answer.
        /// </summary>
        public static void Update(Answers obj)
        {
            bool updateAnswer = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateAnswer = (obj.ObjState != ObjectState.Unchanged);

                if (!updateAnswer)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

            dsAnswers.AnswersDataTable tbl = null;
            if (updateAnswer)
            {
                AnswersTableAdapter adapter = new AnswersTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();

                tbl = new dsAnswers.AnswersDataTable();
                dsAnswers.AnswersRow row = tbl.NewAnswersRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted) && (AnswerID <= 0))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("AnswerID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

                // UserName is required.
                if ((Answer == null) || (Answer.Trim().Length == 0))
                {
                    Errors.Add(new ValidationError("Answer", "Answer is required.", ValidationError.Severity.Error));
                }
                else if (ObjState == ObjectState.Added)
                {

                }

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("Answer: AnswerID={0}, Answer={1}", AnswerID, Answer));
        }

        #endregion

        #endregion

        #region Privates


        #endregion

    }

    /// <summary>
    /// Collection of 0 or more Answer objects.
    /// </summary>

    public class AnswerCollection : List<Answers>
    {
        #region Types

        public class UserComparer : IComparer<Answers>
        {
            public int Compare(Answers a1, Answers a2)
            {
                return (String.Compare(a1.Answer, a2.Answer));
            }
        }

        #endregion

        #region Public Methods

        #region FindByAnswerID

        public Answers FindByAnswerID(int answerID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].AnswerID == answerID)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #region FindAnswerByAnswer

        /// <summary>
        /// Case insensitve compare.
        /// </summary>
        public Answers FindAnswerByAnswer(string answer)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].Answer == answer)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion
    }
}
